<?php
namespace app\controller;

use support\Request;
use support\Response;
use app\model\User;
use app\model\RoomUser;
use app\model\AccountingRecord;

class UserStatsController
{
    /**
     * 获取用户战绩统计
     */
    public function getStats(Request $request): Response
    {
        $userId = $request->get('user_id');
        
        if (!$userId) {
            return json(['success' => false, 'message' => '用户ID不能为空']);
        }

        $user = User::find($userId);
        if (!$user) {
            return json(['success' => false, 'message' => '用户不存在']);
        }

        try {
            // 使用和 getRecords 相同的逻辑：直接从 AccountingRecord 计算
            // 同时统计 user_id 和 target_user_id 的记录，只统计 score 类型
            $roomStats = AccountingRecord::where('type', 'score') // 只统计 score 类型的记录
                ->where(function($query) use ($userId) {
                    $query->where('user_id', $userId)           // 用户给别人记分（支出）
                          ->orWhere('target_user_id', $userId); // 别人给用户记分（收入）
                })
                ->selectRaw('
                    room_id,
                    SUM(CASE 
                        WHEN user_id = ? THEN score 
                        WHEN target_user_id = ? THEN -score 
                        ELSE 0 
                    END) as total_score
                ', [$userId, $userId])
                ->groupBy('room_id')
                ->get();
            
            // 统计所有房间的数据
            $wins = 0;
            $losses = 0;
            $draws = 0;
            $totalScore = 0;
            
            foreach ($roomStats as $stat) {
                $roomScore = (int)$stat->total_score;
                $totalScore += $roomScore;
                
                if ($roomScore > 0) {
                    $wins++;
                } elseif ($roomScore < 0) {
                    $losses++;
                } else {
                    $draws++;
                }
            }
            
            $totalGames = $roomStats->count();
            
            // 计算胜率
            $winRate = $totalGames > 0 ? round(($wins / $totalGames) * 100, 1) : 0;
            
            // 获取排名（基于总积分）
            $rank = User::where('total_score', '>', $user->total_score)->count() + 1;
            
            return json([
                'success' => true,
                'data' => [
                    'wins' => $wins,
                    'losses' => $losses,
                    'draws' => $draws,
                    'winRate' => $winRate,
                    'rank' => $rank,
                    'totalRooms' => $totalGames,
                    'totalScore' => $totalScore
                ]
            ]);
        } catch (\Exception $e) {
            return json(['success' => false, 'message' => '获取战绩失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取用户历史记录
     * 按房间分组，只统计 score 类型的记录
     */
    public function getRecords(Request $request): Response
    {
        $userId = $request->get('user_id');
        // 安全获取分页参数，确保是有效的整数
        $page = (int)$request->get('page', 1);
        $pageSize = (int)$request->get('page_size', 20);
        
        // 验证分页参数的有效性
        if ($page < 1) {
            $page = 1;
        }
        if ($pageSize < 1 || $pageSize > 100) {
            $pageSize = 20; // 默认值，最大100
        }
        
        if (!$userId) {
            return json(['success' => false, 'message' => '用户ID不能为空']);
        }

        try {
            $offset = ($page - 1) * $pageSize;
            
            // 第一步：获取用户参与的所有房间（只统计 score 类型的记录）
            // 需要同时统计 user_id 和 target_user_id 的记录
            // 按 room_id 分组，计算该用户的净分数
            // 如果用户在 user_id：score 是负数，直接累加
            // 如果用户在 target_user_id：score 是负数，需要取反（-score）才能得到正数
            $roomStats = AccountingRecord::where('type', 'score') // 只统计 score 类型的记录
                ->where(function($query) use ($userId) {
                    $query->where('user_id', $userId)           // 用户给别人记分（支出）
                          ->orWhere('target_user_id', $userId); // 别人给用户记分（收入）
                })
                ->selectRaw('
                    room_id,
                    DATE(created_at) as record_date,
                    SUM(CASE 
                        WHEN user_id = ? THEN score 
                        WHEN target_user_id = ? THEN -score 
                        ELSE 0 
                    END) as total_score,
                    MIN(created_at) as first_record_at,
                    MAX(created_at) as last_record_at,
                    COUNT(*) as record_count
                ', [$userId, $userId])
                ->groupBy('room_id', 'record_date')
                ->orderBy('last_record_at', 'desc')
                ->get();
            
            // 按天分组记录
            $recordsByDate = [];
            foreach ($roomStats as $stat) {
                // 获取房间信息
                $room = \app\model\Room::find($stat->room_id);
                if (!$room) {
                    continue; // 如果房间不存在，跳过
                }
                
                // 判断结果
                $result = 'draw';
                if ($stat->total_score > 0) {
                    $result = 'win';
                } elseif ($stat->total_score < 0) {
                    $result = 'loss';
                }
                
                // 格式化日期时间
                $lastRecordAt = \Carbon\Carbon::parse($stat->last_record_at);
                $recordDate = $stat->record_date; // 格式：Y-m-d
                
                if (!isset($recordsByDate[$recordDate])) {
                    $recordsByDate[$recordDate] = [
                        'date' => $recordDate,
                        'date_display' => \Carbon\Carbon::parse($recordDate)->format('Y年m月d日'),
                        'date_short' => \Carbon\Carbon::parse($recordDate)->format('m-d'),
                        'records' => [],
                        'daily_total' => 0,
                        'win_count' => 0,
                        'loss_count' => 0,
                        'draw_count' => 0
                    ];
                }
                
                $recordsByDate[$recordDate]['records'][] = [
                    'id' => $room->id,
                    'room_id' => $room->id,
                    'time' => $lastRecordAt->format('H:i'),
                    'room_name' => $room->name ?? '未知房间',
                    'room_code' => $room->room_code ?? '',
                    'result' => $result,
                    'score_change' => (int)$stat->total_score, // 该房间的总分数变化
                    'record_count' => $stat->record_count, // 该房间的记录数
                    'description' => $room->name ?? '未知房间'
                ];
                
                // 累计每日数据
                $recordsByDate[$recordDate]['daily_total'] += (int)$stat->total_score;
                if ($result === 'win') {
                    $recordsByDate[$recordDate]['win_count']++;
                } elseif ($result === 'loss') {
                    $recordsByDate[$recordDate]['loss_count']++;
                } else {
                    $recordsByDate[$recordDate]['draw_count']++;
                }
            }
            
            // 转换为数组并排序（最新的在前）
            $formattedRecords = array_values($recordsByDate);
            usort($formattedRecords, function($a, $b) {
                return strcmp($b['date'], $a['date']); // 降序
            });
            
            // 获取总天数（用于分页）
            $totalCount = count($formattedRecords);
            
            // 分页处理（按天分页）
            $formattedRecords = array_slice($formattedRecords, $offset, $pageSize);
            
            $hasMore = ($offset + $pageSize) < $totalCount;
            
            return json([
                'success' => true,
                'data' => [
                    'records' => $formattedRecords,
                    'has_more' => $hasMore,
                    'total_count' => $totalCount
                ]
            ]);
        } catch (\Exception $e) {
            return json(['success' => false, 'message' => '获取历史记录失败：' . $e->getMessage()]);
        }
    }
}
